package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.OrdersDto;
import com.itheima.reggie.entity.OrderDetail;
import com.itheima.reggie.entity.Orders;
import com.itheima.reggie.entity.ShoppingCart;
import com.itheima.reggie.mapper.OrderDetailMapper;
import com.itheima.reggie.service.OrderDetailService;
import com.itheima.reggie.service.OrderService;
import com.itheima.reggie.service.ShoppingCartService;
import com.itheima.reggie.service.impl.ShoppingCartServiceImpl;
import com.itheima.reggie.vo.OrderVo;
import com.itheima.reggie.vo.PageOrder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 订单
 */
@Slf4j
@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private OrderService orderService;
    @Autowired
    private OrderDetailService orderDetailService;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private ShoppingCartService shoppingCartService;

    /**
     * 用户下单
     * @param orders
     * @return
     */
    @PostMapping("/submit")
    public R<String> submit(@RequestBody Orders orders){
        log.info("订单数据：{}",orders);
        orderService.submit(orders);
        return R.success("下单成功");
    }

    /**
     * 订单分页查询
     * @param page
     * @param pageSize
     * @param number
     * @param beginTime
     * @param endTime
     * @return
     */
    @GetMapping("/page")
    public  R<Page<OrdersDto>> page(int page, int pageSize, String number, String beginTime,String endTime){
        //构造分页构造器对象
        Page<Orders> pageInfo = new  Page<>(page,pageSize);
        //条件构造器
        LambdaQueryWrapper<Orders> queryWrapper = new  LambdaQueryWrapper<>();
        //添加过滤条件
        queryWrapper.like(number != null,Orders::getNumber,number);
        queryWrapper.between(beginTime!=null && endTime!=null ,
                Orders::getOrderTime,beginTime,endTime);
        //添加排序条件
        queryWrapper.orderByDesc(Orders::getOrderTime);
        //执行分页查询
        orderService.page(pageInfo,queryWrapper);
        Page<OrdersDto> ordersDtoPage = new  Page<OrdersDto>();
        BeanUtils.copyProperties(pageInfo,ordersDtoPage,"records");
        //完成订单详情的集合封装
        List<OrdersDto> ordersDtos = pageInfo.getRecords().stream().map(orders -> {
            OrdersDto ordersDto = new OrdersDto();
            //订单基本信息封装到ordersDto
            BeanUtils.copyProperties(orders, ordersDto);
            //订单详情集合
            LambdaQueryWrapper<OrderDetail> orderDetailLambdaQueryWrapper = new  LambdaQueryWrapper<>();
            orderDetailLambdaQueryWrapper.eq(OrderDetail::getOrderId, orders.getId());
            List<OrderDetail> ordersDetailList = orderDetailService.list(orderDetailLambdaQueryWrapper);
            ordersDto.setOrderDetails(ordersDetailList);
            return  ordersDto;
        }).collect(Collectors.toList());
        //手动封装ordersDtos分页中的records属性
        ordersDtoPage.setRecords(ordersDtos);
        return  R.success(ordersDtoPage);
    }

    @PutMapping
    public R<String> update(@RequestBody Orders orders){
        log.info("订单数据：{}",orders);
        orderService.updateById(orders);
        return R.success("订单状态修改成功");
    }

    @GetMapping("/userPage")
    public R<PageOrder> userPage(int page, int pageSize){
        // 创建分页对象
        Page<Orders> orderPage = new Page<>(1, 10);
        // 查询订单信息
        LambdaQueryWrapper<Orders> orderLambdaQueryWrapper = new LambdaQueryWrapper<>();
        orderLambdaQueryWrapper.eq(Orders::getUserId, BaseContext.getCurrentId());
        orderService.page(orderPage, orderLambdaQueryWrapper);

        // 封装分页结果
        PageOrder pageOrder = new PageOrder();
        pageOrder.setSize((int)orderPage.getSize());
        pageOrder.setTotal((int) orderPage.getTotal());
        List<OrderVo> orderVoList = new ArrayList<>();

        // 查询订单详细信息
        orderPage.getRecords().forEach(order -> {
            OrderVo orderVo = new OrderVo();
            BeanUtils.copyProperties(order, orderVo); // 复制订单信息
            LambdaQueryWrapper<OrderDetail> detailLambdaQueryWrapper = new LambdaQueryWrapper<>();
            detailLambdaQueryWrapper.eq(OrderDetail::getOrderId, order.getId());
            orderVo.setOrderDetails(orderDetailMapper.selectList(detailLambdaQueryWrapper));
            orderVoList.add(orderVo);
        });

        pageOrder.setRecords(orderVoList);
        return R.success(pageOrder);
    }

    /**
     * 再来一单
     * @param orders
     * @return
     */
    @PostMapping("/again")
    public R<String> again(@RequestBody Orders orders){
        log.info("订单数据：{}",orders);

        // 把菜品数据插入到购物车中
        String orderId = orderService.getById(orders.getId()).getNumber();
        LambdaQueryWrapper<OrderDetail> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(OrderDetail::getOrderId, orderId);
        List<OrderDetail> orderDetailList = orderDetailService.list(wrapper);
        ShoppingCart shoppingCart = new ShoppingCart();
        for (OrderDetail orderDetail : orderDetailList){
            BeanUtils.copyProperties(orderDetail, shoppingCart);
            shoppingCart.setUserId(BaseContext.getCurrentId());
            shoppingCart.setCreateTime(LocalDateTime.now());
            shoppingCartService.save(shoppingCart);
        }

        return R.success("菜品以加入购物车");
    }

}